package com.cn.kabalifeuser.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;


/**
 * Created by xiaolin on 2018/9/19.
 * function
 */

public abstract class LazyFragment<V, T extends BasePresenter<V>> extends BaseFragment {
    public int pagehttp=1;
    public int pageNum=10;
    protected T mPresenter;

    /**
     * 控件是否已经初始化
     */
    private boolean isCreateView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //判断是否使用MVP模式
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        isCreateView = true;
        if (getUserVisibleHint()) {
            initPrepare();
        }
        return view;
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     * 此方法在控件初始化前调用，所以不能在此方法中直接操作控件会出现空指针
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser)
            initPrepare();
    }

    //同步锁
    private synchronized void initPrepare() {
        if (!isCreateView) return;
        onUserVisible();
    }

    //用于创建Presenter和判断是否使用MVP模式(由子类实现)
    protected abstract T createPresenter();

    /**
     * 当视图初始化
     * 并且对用户可见
     * 时候去真正的加载数据
     */
    protected abstract void onUserVisible();


}
